package com.bsj.power.pls.config.net.netty.common.client;

import cn.hutool.core.util.HexUtil;
import com.bsj.consumerQ.until.ExceptionUntil;
import com.bsj.power.common.util.ExceptionUtil;
import com.bsj.power.common.util.SpringUtil;
import com.bsj.power.pls.config.net.netty.TcpClientNet;
import com.bsj.power.pls.config.net.netty.common.timer.ScheduledResetThread;
import com.bsj.power.pls.queue.service.impl.QueueRTKBroadcastImpl;
import com.bsj.power.pls.queue.service.impl.tactic.SequentialConsumeQueue;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * @author yinhao
 * @version 1.0
 * @description RTK数据接收
 * @date 2024/10/11
 */
@Slf4j
public class HandleClientRTK extends SimpleChannelInboundHandler<Object> {

    private static QueueRTKBroadcastImpl queueRTKBroadcast;

    static {
        queueRTKBroadcast = SpringUtil.getBean(QueueRTKBroadcastImpl.class);
    }

    public HandleClientRTK() {}

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, Object msg) throws Exception {
        //转变为数据
        byte[] data = null;
        try {
            data = (byte[]) msg;
        } catch (ClassCastException e) {
            log.error("Data conversion error: {}", ExceptionUntil.getErrorStr(e));
            return;
        }
        log.info("RTK广播数据接收: {}", HexUtil.encodeHexStr(data, false));
//        queueRTKBroadcast.doPush(data);
        byte emp = data[3];
        if (emp == 0x41) {
            //星历数据直接过滤出来,不写入消费队列
            SequentialConsumeQueue.addEphByte(data);
        } else {
            SequentialConsumeQueue.putData(data);
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("client ctx = {}", ctx);
    }

    /**
     * 处理异常, 一般是需要关闭通道
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error(ExceptionUtil.getStackStr(cause));
        ctx.close();
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);

        log.info("与服务器断开");
        ctx.close();
        //重连
//        TcpClientNet tcpClientNet = new TcpClientNet(RTKTcpClientConstant.ip, RTKTcpClientConstant.port);
//        tcpClientNet.initClient();
//        tcpClientNet.doConnect();
        ScheduledResetThread.tcpClientNet.doConnect();
    }
}
